/**
 *====================================================
 * 文件名称: LoginActionFinanceImpl.java
 * 修订记录：
 * No    日期				作者(操作:具体内容)
 * 1.    2015年9月23日			chenxy(创建:创建文件)
 *====================================================
 * 类描述：(说明未实现或其它不应生成javadoc的内容)
 */
package com.yuexunit.finance.context;

import java.util.List;

import org.apache.commons.lang3.StringUtils;
import org.hibernate.criterion.DetachedCriteria;
import org.hibernate.criterion.Restrictions;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.yuexunit.account.action.v2.AccountActionApi;
import com.yuexunit.account.action.v2.model.Account;
import com.yuexunit.account.action.v3.AccountSessionActionApi;
import com.yuexunit.account.entity.AccountNameEntity;
import com.yuexunit.account.entity.AccountSessionEntity;
import com.yuexunit.account.spi.LoginCommand;
import com.yuexunit.core.exception.InvalidSessionException;
import com.yuexunit.finance.member.entity.EnterpriseEntity;
import com.yuexunit.finance.member.entity.LogisticsClerkEntity;
import com.yuexunit.finance.member.entity.LogisticsCompanyEntity;
import com.yuexunit.finance.member.service.EnterpriseService;
import com.yuexunit.finance.member.service.LogisticsClerkService;
import com.yuexunit.finance.member.service.LogisticsCompanyService;
import com.yuexunit.inject.ComponentFactory;
import com.yuexunit.inject.annotation.Implements;
import com.yuexunit.organization.OrganizationActionApi;
import com.yuexunit.organization.dto.InquireEmployeeDetailOutput;
import com.yuexunit.persist.PersistUtil;
import com.yuexunit.tenant.TenantActionApi;
import com.yuexunit.tenant.dto.TenantIdOutput;

/**
 * @ClassName: LoginActionFinanceImpl implements LoginCommand
 * @Description: TODO(这里用一句话描述这个类的作用)
 * @author chenxy
 * @date 2015年9月23日 下午7:38:35
 */
@Implements(LoginCommand.class)
public class LoginActionFinanceImpl implements LoginCommand {

	private TenantActionApi tenantAction = ComponentFactory.loadClass(TenantActionApi.class);

	private AccountSessionActionApi sessionAction = ComponentFactory.loadClass(AccountSessionActionApi.class);

	private OrganizationActionApi organizationAction = ComponentFactory.loadClass(OrganizationActionApi.class);

	private EnterpriseService enterpriseService = ComponentFactory.loadClass(EnterpriseService.class);

	private LogisticsCompanyService logisticsCompanyService = ComponentFactory.loadClass(LogisticsCompanyService.class);

	private LogisticsClerkService logisticsClerkService = ComponentFactory.loadClass(LogisticsClerkService.class);

	private FinanceRoleEnum validateFinanceRole(String appKey) {
		if (FinanceConstant.APPKEY_ENTERPRISE_ANDROID.equals(appKey)) {
			return FinanceRoleEnum.ENTERPRISE;
		}
		if (FinanceConstant.APPKEY_ENTERPRISE_IOS.equals(appKey)) {
			return FinanceRoleEnum.ENTERPRISE;
		}
		if (FinanceConstant.APPKEY_ENTERPRISE_WEB.equals(appKey)) {
			return FinanceRoleEnum.ENTERPRISE;
		}
		if (FinanceConstant.APPKEY_LOGISTICS_ANDROID.equals(appKey)) {
			return FinanceRoleEnum.LOGISTICS;
		}
		if (FinanceConstant.APPKEY_LOGISTICS_IOS.equals(appKey)) {
			return FinanceRoleEnum.LOGISTICS;
		}
		if (FinanceConstant.APPKEY_LOGISTICS_WEB.equals(appKey)) {
			return FinanceRoleEnum.LOGISTICS;
		}
		if (FinanceConstant.APPKEY_PLATFORM_WEB.equals(appKey)) {
			return FinanceRoleEnum.PLATFORM;
		}
		if (FinanceConstant.APPKEY_PLATFORM_IOS.equals(appKey)) {
			return FinanceRoleEnum.PLATFORM;
		}
		if (FinanceConstant.APPKEY_PLATFORM_ANDROID.equals(appKey)) {
			return FinanceRoleEnum.PLATFORM;
		}
		return null;
	}

	@Override
	public void afterLogin(String sessionUuid, Long accountId, String appKey, String website) {
		FinanceRoleEnum financeRole = validateFinanceRole(appKey);
		if (validateFinanceRole(appKey) == null) {
			throw new InvalidSessionException("未知的帐户类型,appKey不允许为空");
		}
		System.out.println(sessionUuid);
		System.out.println(accountId);
		System.out.println(appKey);
		System.out.println(website);
		TenantIdOutput tenant = tenantAction.inquireTenantByAccountId(accountId);
		Long tenantId = tenant.getTenantId();
		if (tenantId == null) {
			throw new InvalidSessionException("未知的帐号类型信息,租户信息为空");
		}

		FinanceSessionAdditional additional = new FinanceSessionAdditional();
		AccountActionApi accountAction = ComponentFactory.loadClass(AccountActionApi.class);
		Account account = accountAction.inquireAccountDetail(accountId);
		additional.setFullName(account.getFullName());
		if(!StringUtils.isEmpty(website)){
			additional.setIsApp("app");
		}

//		DetachedCriteria dc = DetachedCriteria.forClass(AccountNameEntity.class);
//		dc.add(Restrictions.eq("accountId", accountId));
//		List<AccountNameEntity> anes = PersistUtil.get(dc);
//		AccountNameEntity ane = anes.get(0);
//		if (ane)FinanceConstant
		
		if (financeRole == FinanceRoleEnum.ENTERPRISE) {
			LogisticsCompanyEntity lce = logisticsCompanyService.inquireTenantLogisticsCompany(tenantId);
			if (lce != null) {
				throw new InvalidSessionException("该账号不允许在客户端登陆");
			}
			if (FinanceConstant.DEFAULT_PLATFORM_WEB_TENANT.longValue() == tenantId) {
				throw new InvalidSessionException("该账号不允许在客户端登陆");
			}
			EnterpriseEntity enterprise = enterpriseService.inquireTenantEnterprise(tenantId, true, null);
			if (enterprise != null && !enterprise.getEnabled()) {
				throw new InvalidSessionException("该帐号注册的企业已经被移除");
			}
			if (enterprise != null) {
				additional.setEnterpriseId(enterprise.getEnterpriseId());
				additional.setEnterpriseName(enterprise.getEnterpriseName());
			}
		} else if (financeRole == FinanceRoleEnum.LOGISTICS) {
			LogisticsCompanyEntity company = logisticsCompanyService.inquireTenantLogisticsCompany(tenantId);
			additional.setCompanyId(company.getCompanyId());
			List<LogisticsClerkEntity> clerks = logisticsClerkService.inqueryLogisticsClerkList(company.getCompanyId(), accountId);
			if (clerks != null && !clerks.isEmpty()) {
				additional.setClerkId(clerks.get(0).getClerkId());
			}
		} else {
			if (FinanceConstant.DEFAULT_PLATFORM_WEB_TENANT.longValue() != tenantId.longValue()) {
				throw new InvalidSessionException("该帐号不允许在平台登陆");
			}
			try {
				InquireEmployeeDetailOutput employeeInfo = organizationAction.inquireAccountEmployeeInfo(tenantId, accountId);
				if (employeeInfo != null) {
					additional.setRegion(employeeInfo.getCurrentArea());
				}
			} catch (Exception e) {
			}
		}
		if (StringUtils.isBlank(additional.getFullName())) {
			throw new InvalidSessionException("登陆失败帐号名称为空");
		}
		GsonBuilder builder = new GsonBuilder();
		Gson gson = builder.create();
		sessionAction.bindTenantIdToSession(sessionUuid, tenantId, appKey, gson.toJson(additional));
	}
	
	public void afterLogin1(String sessionUuid, Long accountId, String appKey, AccountSessionEntity ase) {
		FinanceRoleEnum financeRole = validateFinanceRole(appKey);
		if (validateFinanceRole(appKey) == null) {
			throw new InvalidSessionException("未知的帐户类型,appKey不允许为空");
		}
		System.out.println(sessionUuid);
		System.out.println(accountId);
		System.out.println(appKey);
		TenantIdOutput tenant = tenantAction.inquireTenantByAccountId(accountId);
		Long tenantId = tenant.getTenantId();
		if (tenantId == null) {
			throw new InvalidSessionException("未知的帐号类型信息,租户信息为空");
		}

		FinanceSessionAdditional additional = new FinanceSessionAdditional();
		AccountActionApi accountAction = ComponentFactory.loadClass(AccountActionApi.class);
		Account account = accountAction.inquireAccountDetail(accountId);
		additional.setFullName(account.getFullName());

		if (financeRole == FinanceRoleEnum.ENTERPRISE) {
			EnterpriseEntity enterprise = enterpriseService.inquireTenantEnterprise(tenantId, true, null);
			if (enterprise != null && !enterprise.getEnabled()) {
				throw new InvalidSessionException("该帐号注册的企业已经被移除");
			}
			if (enterprise != null) {
				additional.setEnterpriseId(enterprise.getEnterpriseId());
				additional.setEnterpriseName(enterprise.getEnterpriseName());
			}
		} else if (financeRole == FinanceRoleEnum.LOGISTICS) {
			LogisticsCompanyEntity company = logisticsCompanyService.inquireTenantLogisticsCompany(tenantId);
			additional.setCompanyId(company.getCompanyId());
			List<LogisticsClerkEntity> clerks = logisticsClerkService.inqueryLogisticsClerkList(company.getCompanyId(), accountId);
			if (clerks != null && !clerks.isEmpty()) {
				additional.setClerkId(clerks.get(0).getClerkId());
			}
		} else {
			if (FinanceConstant.DEFAULT_PLATFORM_WEB_TENANT.longValue() != tenantId.longValue()) {
				throw new InvalidSessionException("该帐号不允许在平台登陆");
			}
			try {
				InquireEmployeeDetailOutput employeeInfo = organizationAction.inquireAccountEmployeeInfo(tenantId, accountId);
				if (employeeInfo != null) {
					additional.setRegion(employeeInfo.getCurrentArea());
				}
			} catch (Exception e) {
			}
		}
		if (StringUtils.isBlank(additional.getFullName())) {
			throw new InvalidSessionException("登陆失败帐号名称为空");
		}
		GsonBuilder builder = new GsonBuilder();
		Gson gson = builder.create();
		
		ase.setTenantId(tenantId);
		ase.setExtra(gson.toJson(additional));
	}
}
